﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Xml;
using BoYuanCore.DBServices.Base;
using BoYuanCore.Entities;
using BoYuanCore.Framework;
using BoYuanCore.Framework.MemoryCache;
using BoYuanCore.Web;
using BoYuanCore.WebUI.Code;
using FineUICore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;

namespace BoYuanCore.WebUI.Areas.Admin.Controllers
{
    
    public class HomeController : BaseController
    {
        private readonly ILogger<HomeController> _logger;
        private readonly IHostingEnvironment _env;
        private readonly ICachingProvider _iCachingProvider;

        public HomeController(ILogger<HomeController> logger, IHostingEnvironment env,ICachingProvider iCachingProvider) : base(logger)
        {
            _logger = logger;
            _env = env;
            _iCachingProvider = iCachingProvider;
        }

        // GET: Home
        public IActionResult Index()
        {
            ViewBag.UserShowName = string.Empty;
            ViewBag.UserShowHead = string.Empty;

            long userid = GetUserID();
            if (userid > 0) 
            {
                var user=DBServices.SysAdmin.GetAdminByCache(userid, _iCachingProvider) ;
                ViewBag.UserShowName = string.IsNullOrEmpty(user.RealName)?user.LoginName:user.RealName;
                ViewBag.UserShowHead = user.Photo;
            }

            LoadData();

            return View("Index");
        }
          

        #region Views

        // GET: Themes
        public IActionResult Themes()
        {
            return View();
        }

        // GET: Loading
        public IActionResult Loading()
        {
            return View();
        }

        // GET: Main
        public IActionResult Main()
        {
            return View();
        }


        // GET: Home/Error
        public IActionResult Error()
        {
            ViewBag.ErrorMessage = "Error";

            var exception = HttpContext.Features.Get<Microsoft.AspNetCore.Diagnostics.IExceptionHandlerFeature>();
            if (exception != null)
            {
                ViewBag.ErrorMessage = exception.Error.Message;
            }

            ViewBag.RequestId = System.Diagnostics.Activity.Current?.Id ?? HttpContext.TraceIdentifier;

            return View();
        }



        #endregion

        #region LoadData

        private string _cookieMenuStyle = "tree";

        private string _cookieDisplayMode = "normal";
        private string _cookieMainTabs = "multi";
        private string _cookieLang = "zh_CN";

        // 示例数
        private int _examplesCount = 0;

        private void LoadData()
        {
            string cookie = String.Empty;

            _cookieMenuStyle = "plaintree";
            _cookieDisplayMode = "normal";

            // 从Cookie中读取 - 语言
            cookie = Request.Cookies["Language"];
            if (!String.IsNullOrEmpty(cookie))
            {
                _cookieLang = cookie;
            }

            // 从Cookie中读取 - 主选项卡标签
            cookie = Request.Cookies["MainTabs"];
            if (!String.IsNullOrEmpty(cookie))
            {
                _cookieMainTabs = cookie;
            }

            LoadTreeMenuData();

            ViewBag.CookieMenuStyle = _cookieMenuStyle;
            ViewBag.CookieIsBase = Constants.IS_BASE;
            ViewBag.CookieDisplayMode = _cookieDisplayMode;
            ViewBag.CookieMainTabs = _cookieMainTabs;
            ViewBag.CookieLang = _cookieLang;

            ViewBag.ProductVersion = GlobalConfig.ProductVersion;
            ViewBag.ExamplesCount = _examplesCount.ToString();
        }

        private void LoadTreeMenuData()
        {
            IList<TreeNode> nodes = new List<TreeNode>();

            var moduleList = DBServices.SysModule.GetSysModuleListByCache(_iCachingProvider, HaveButtonPermissions);
            long userid = GetUserID();
            List<long> moduleIds = DBServices.SysModulePermissions.GetPermissionsByCache(userid, _iCachingProvider);//获取当前用户的对应角色的页面组件id集合
            var list = moduleList.Where(p => moduleIds.Contains(p.ID) && string.IsNullOrEmpty(p.ButtonID) && p.IsHidden == false).OrderBy(p => p.Sort).ToList();
            var parentlist = list.Where(p => p.ParentID == 0).OrderBy(p => p.Sort).ToList();

            TreeNode node;
            foreach (var module in parentlist)
            {
                node = new TreeNode();

                node.NodeID = module.ID.ToString();
                node.Text = module.PageTitle;
                node.NavigateUrl = module.Url;

                if (!string.IsNullOrEmpty(module.Icon)) node.IconUrl = "/" + module.Icon;
                if (!string.IsNullOrEmpty(module.FontIcon)) node.IconFont = (IconFont)Enum.Parse(typeof(IconFont), module.FontIcon);

                node.Expanded = true;//默认节点都为展开

                CreateTreeNodes(list, node);
                nodes.Add(node);
            }

            // 视图数据
            ViewBag.TreeMenuNodes = nodes.ToArray();
        }
        private static void CreateTreeNodes(List<Entities.SysModule> moduleList, TreeNode parentNode)
        {
            var list = moduleList.Where(p => p.ParentID.ToString() == parentNode.NodeID && string.IsNullOrEmpty(p.ButtonID) && p.IsHidden == false).OrderBy(p => p.Sort).ToList();

            if (list.Count == 0) return;

            TreeNode node;
            foreach (var module in list)
            {
                node = new TreeNode();

                node.NodeID = module.ID.ToString();
                node.Text = module.PageTitle;
                node.NavigateUrl = module.Url;

                if (!string.IsNullOrEmpty(module.Icon)) node.IconUrl = "/" + module.Icon;
                if (!string.IsNullOrEmpty(module.FontIcon)) node.IconFont = (IconFont)Enum.Parse(typeof(IconFont), module.FontIcon);

                node.Expanded = true;//默认节点都为展开

                CreateTreeNodes(moduleList, node);
                parentNode.Nodes.Add(node);
            }
        }


        #endregion

        #region EditPage FacePhoto 个人用户信息编辑相关

        public IActionResult FacePhoto()
        {
            return View();
        }

        public IActionResult Edit()
        {
            long userid = GetUserID();
            if (userid > 0)
            {
                var admin = DBServices.SysAdmin.GetAdminByCache(userid, _iCachingProvider); 
                ViewBag.loginName = admin.LoginName;
                ViewBag.realname = admin.RealName;
                ViewBag.photo = admin.Photo;
            }
            else
            {
                ViewBag.loginName = string.Empty;
                ViewBag.realname = string.Empty;
                ViewBag.photo = string.Empty;
            }

            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult PhotoUpload(IFormFile filePhoto, IFormCollection fc)
        {
            string errroInfo = string.Empty;

            using (UpLoadContext upLoad = new UpLoadContext(filePhoto, _env))
            {
                // 生成缩略图1
                upLoad.Img_THeight = 100;
                upLoad.Img_TWidth = 100;
                upLoad.FileName_url = string.Empty;//清空指定路径，并使用默认方式上传

                if (!upLoad.UpLoadIMG())//上传缩略图
                {
                    errroInfo += upLoad.Error;
                    AlertError("上传图片失败," + errroInfo, false);
                    return UIHelper.Result();
                }
                else
                {
                    UIHelper.Image("imgPhoto").ImageUrl(upLoad.FileName_url);
                    UIHelper.HiddenField("hd_photo").Text(upLoad.FileName_url);
                }
            }

            // 清空文件上传组件（上传后要记着清空，否则点击提交表单时会再次上传！！）
            UIHelper.FileUpload("filePhoto").Reset();
            return UIHelper.Result();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Button_saveEdit_OnClick(IFormCollection fc)
        {
            string newPwd = string.Empty;
            //验证
            if (fc["Password_new1"].ToString().Length > 0 && fc["Password_old"].ToString().Length == 0)
            {
                NotifyError("请输入老密码");
                return UIHelper.Result(); 
            }
            else if (fc["Password_new1"].ToString().Length == 0 && fc["Password_old"].ToString().Length > 0)
            {
                NotifyError("请输入新密码");
                return UIHelper.Result();
            }
            else if (fc["Password_new1"].ToString().Length > 0 && fc["Password_old"].ToString().Length > 0)
            {
                if (fc["Password_new1"].ToString() != fc["Password_new2"].ToString())
                {
                    NotifyError("新密码和重复密码要一致");
                    return UIHelper.Result();
                }
                else
                {
                    if (fc["Password_new1"].ToString().Length < 6)
                    {
                        NotifyError("密码长度至少是6位");
                        return UIHelper.Result();
                    }
                    newPwd = Security.MD5Helper.GetMd5Pwd(fc["Password_new1"].ToString());
                }
            }
            
            string photo = fc["hd_photo"].ToString();

            long adminId = GetUserID();

            if (adminId == 0)
            {
                return UIHelper.Result();
            }
            

            bool updateSuccess = false;

            if (newPwd.Length > 0)
            {
                string oldPwd = Security.MD5Helper.GetMd5Pwd(fc["Password_old"].ToString());
                updateSuccess = FreeSqlHelper.Update<SysAdmin>(
                    p => new SysAdmin { Photo = photo, Password = newPwd, RealName = fc["realname"].ToString() },
                    p => p.ID == adminId && p.Password == oldPwd) > 0;
            }
            else
            {
                updateSuccess = FreeSqlHelper.Update<SysAdmin>(
                        p => new SysAdmin { Photo = photo, RealName = fc["realname"].ToString() },
                        p => p.ID == adminId) > 0;
            }

            if (updateSuccess)
            {
                DBServices.SysAdmin.RemoveCache(adminId, _iCachingProvider);//更新缓存

                string oldPhoto = fc["hd_oldPhoto"].ToString();
                if (oldPhoto.Length > 0 && photo != oldPhoto)
                {
                    //删除老图片
                    if (!oldPhoto.Contains("res/images/head") && oldPhoto.Length > 0)//排除默认图片
                        UpLoadContext.DeleteFile(oldPhoto, _env);
                }
                AlertInfor("修改成功", true);
            }
            else
            {
                NotifyError("修改失败");
            }
            return UIHelper.Result();
        }

        #endregion

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Logout()
        {

            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
            HttpContext.Session.Clear();

            //string url= Url.Action("Index", "Login", new { area = UrlAddress.AreaAdmin });

            return RedirectToAction("Index", "Login", new { area = UrlAddress.AreaAdmin });
        }
    }
}